from datetime import datetime
import json
import os

from core.gitee_api import GiteeAPI
from llm import LLMClient


class ReportGenerator:
    def __init__(self, token,ollama_url):
        self.llm_client = LLMClient(base_url=ollama_url)
        self.api = GiteeAPI(token)

    def generate_release_report(self, repo_url):
        # 提取 owner 和 repo 名称
        repo_path = repo_url.replace("https://gitee.com/", "").strip("/")
        owner, repo = repo_path.split("/")

        release_info = self.api.get_latest_release(owner, repo)
        if release_info:
            report = {
                "repository": repo_url,
                "latest_version": release_info.get("tag_name"),
                "release_name": release_info.get("name"),
                "published_at": release_info.get("created_at"),
                "release_notes": release_info.get("body", "No release notes provided.")
            }
            report_file = f"gitee_release_report_{release_info['tag_name']}.json"
            with open(report_file, "w") as file:
                # 将ensure_ascii设置为False可以确保非ASCII字符以原始形式保存。
                json.dump(report, file, indent=4, ensure_ascii=False)
            print(f"Report generated: {report_file}")
        else:
            print("Failed to generate report.")

    def generate_summary_report(self, daily_report_file):
        """读取每日进展的 Markdown 文件并生成汇总报告"""
        with open(daily_report_file, "r", encoding="utf-8") as f:
            content = f.read()

        # 调用 LLM 模型生成汇总报告
        summary = self.llm_client.summarize(content)

        # 保存汇总报告
        summary_file = daily_report_file.replace(".md", "_summary.md")
        with open(summary_file, "w", encoding="utf-8") as f:
            f.write(summary)

        print(f"Summary report generated: {summary_file}")
        return summary_file


    def generate_daily_report(self, owner, repo):
        """生成每日进展的 Markdown 文件"""
        issues = self.api.get_issues(owner, repo)
        prs = self.api.get_pull_requests(owner, repo)

        # 文件名：<repo_name>_<YYYY-MM-DD>.md
        date = datetime.now().strftime("%Y-%m-%d")
        file_name = f"reports/{repo}_{date}.md"
        os.makedirs("reports", exist_ok=True)

        # 写入 Markdown 文件
        with open(file_name, "w", encoding="utf-8") as f:
            f.write(f"# Daily Report: {repo} ({date})\n\n")
            f.write("## Issues\n")
            for issue in issues:
                f.write(f"- [{issue['title']}]({issue['html_url']})\n")

            f.write("\n## Pull Requests\n")
            for pr in prs:
                f.write(f"- [{pr['title']}]({pr['html_url']})\n")

        print(f"Report generated: {file_name}")
        return file_name